import arb.soundcipher.*;

void generateNotes(int count, int leave) {
  println("# Calculating plot points...");
  ArrayList<PVector> notesCurve = finder.calcNotesPoints();
  ArrayList<PVector> durationsCurve = finder.calcDurationsPoints();
  ArrayList<PVector> velocityesCurve = finder.calcVelocityesPoints();

  int size = notesCurve.size();

  println("# Getting tracks fractal dimmension...");
  float aimNotesDim = finder.calcSlope(finder.calcLogParams(finder.measureCurve(notesCurve)));
  float aimDuratiobsDim = finder.calcSlope(finder.calcLogParams(finder.measureCurve(durationsCurve)));
  float aimVelocityesDim = finder.calcSlope(finder.calcLogParams(finder.measureCurve(velocityesCurve)));
  println("notes dim: " + aimNotesDim);
  println("duration dim: " + aimDuratiobsDim);
  println("velocity dim: " + aimVelocityesDim);  
  ArrayList<PVector> tempNotesCurve = notesCurve;
  ArrayList<PVector> tempDurationsCurve = durationsCurve;
  ArrayList<PVector> tempVelocityesCurve = velocityesCurve;
  
  println("# Generating new notes...");
  for (int i = 0; i < count; i++) {
    tempNotesCurve = finder.nextNoteRandom(tempNotesCurve, aimNotesDim);
    tempDurationsCurve = finder.nextDurationRandom(tempDurationsCurve, aimDuratiobsDim);
    tempVelocityesCurve = finder.nextVelocityRandom(tempVelocityesCurve, aimVelocityesDim);
  }
  println("# Converting notes to MIDI...");
  //println("leave len: " + leaveLen);
  size -= leaveLen;
  ArrayList<PVector> newNotes = finder.calcPointNotes(tempNotesCurve, size);
  ArrayList<PVector> newDurations = finder.calcPointNotes(tempDurationsCurve, size);
  ArrayList<PVector> newVelocityes = finder.calcPointNotes(tempVelocityesCurve, size);

  playNotes(newNotes, newDurations, newVelocityes);
}

void playNotes(ArrayList<PVector> notes, ArrayList<PVector> durations, ArrayList<PVector> velocityes) {
  println("# Scoring notes... ");
  score.empty();
  float nextDelta = 0;
  for (int i = 0; i < notes.size(); i++) {

    float velocity = velocityes.get(i).y;
    if (notes.get(i).y == 128.0) {
      velocity = 0;
    }
    //println("note: " + notes.get(i).y + " duration: " + getDurationVal(durations.get(i).y) + " velocity: " + velocity);
    score.addNote(nextDelta, notes.get(i).y, velocity, getDurationVal(durations.get(i).y));
    nextDelta += getDurationVal(durations.get(i).y)*4;
  }
  // empty note because of cut off
  score.addNote(nextDelta+1, 0, 0, 1);
  println("# Play notes");
  score.play();
  if (doSaveFile) {
    score.writeMidiFile(dataPath("")+"/generated_"+currentTrackName);
  }
}

